package tech.horgee.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.horgee.entity.Dict;
import tech.horgee.mapper.DictMapper;
import tech.horgee.utils.AssertUtil;
import tech.horgee.utils.CacheUtils;

import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 字典表 服务类
 *
 * @author haojun
 * @since 2024-01-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DictService {
    private final DictMapper mapper;

    private static final String DICT_BY_ID = "DictById";

    /**
     * 分页查询列表
     *
     * @param page   分页对象
     * @param entity 查询实体
     * @return 所有数据
     */
    public Page<Dict> page(Page<Dict> page, Dict entity) {
        return mapper.selectPage(page, Optional.ofNullable(entity).orElse(new Dict()).wrapper());
    }

    /**
     * 不分页查询列表
     *
     * @param entity 实体对象
     * @return 查询结果
     */
    public List<Dict> list(Dict entity) {
        return mapper.selectList(Optional.ofNullable(entity).orElse(new Dict()).wrapper());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @Cacheable(cacheNames = DICT_BY_ID, key = "#id")
    public Dict getById(Long id) {
        return mapper.selectById(id);
    }

    /**
     * 新增单条数据
     *
     * @param entity 实体对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(Dict entity) {
        mapper.insert(entity);
    }

    /**
     * 修改单条数据
     *
     * @param entity 实体对象
     */
    @CacheEvict(cacheNames = DICT_BY_ID, key = "#entity.id")
    @Transactional(rollbackFor = Exception.class)
    public void update(Dict entity) {
        AssertUtil.onlyOne(mapper.updateById(entity));
    }

    /**
     * 批量删除数据
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Set<Long> ids) {
        AssertUtil.updated(mapper.deleteBatchIds(ids));
        ids.forEach(id -> CacheUtils.evict(DICT_BY_ID, id));
    }

}
